
// Common functions for mobilize! administration infrastructure
//
// ultimoistante of StartupSolutions.it
// started writing on March 09, 2012

var BASE_URL = "http://localhost:8080";


function createCORSRequest(method, url)
	{
	var request = new XMLHttpRequest();
	if (!request)
		{
		alert('CORS not supported');
		}
	else
		{
		request.open(method, url, false);
		}
	/*if ("withCredentials" in xhr)
		{
		// XHR for Chrome/Safari/Firefox.
		// alert("nuovo");
		xhr.open(method, url);
		}
	else if (typeof XDomainRequest != "undefined")
		{
		// XDomainRequest for IE.
		xhr = new XDomainRequest();
		xhr.open(method, url);
		}
	else
		{
		// CORS not supported.
		xhr = null;
		}*/
	return request;
	}
	


function requestAppList()
	{
	//var xhr = createCORSRequest("GET", "http://locahost:8080/applist");
	var xhr = new XMLHttpRequest();
	if (!xhr)
		{
		alert('CORS not supported');
		}
	xhr.open('GET', BASE_URL + "/applist", true);
	// Response handlers
	xhr.onreadystatechange = function() {
		if(xhr.readyState == 4)
			{
			if (xhr.status == 200)
				{
				dumpAppList($.parseJSON(xhr.responseText));
				}
			else
				{
				alert("Invocation Errors Occured " + invocation.readyState + " and the status is " + invocation.status);
				}
			}
		};
	xhr.onerror = function() {
		alert('Error requesting application list');
		};

	xhr.send();
	}
	

function dumpAppList(data)
	{
	$("#content").html("");

	$("#content").append("<p>Application list [dumpdata]</p>");
	//
	$("#content").append("<ul data-role='listview' data-inset='true' class='ui-listview ui-listview-inset ui-corner-all ui-shadow'>");
	//
	for(var i=0; i < data.applist.length; i++)
		$("#content ul").append("<li><a href='javascript:editApp(" + data.applist[i].app_id + ");' data-transition='slide'>" + data.applist[i].app_name + "</a></li>");
		//$("#content ul").append("<li><a href='app_edit.jsp?appId=" + data.applist[i].app_id + "' data-transition='slide'>" + data.applist[i].app_name + "</a></li>");
	//
	$("#content ul").listview();
	}
	

function editApp(id)
	{
	//alert(id);
	$.mobile.changePage("#appedit_page");
	requestAppData(id);
	}


function requestAppData(id)
	{
	var xhr = new XMLHttpRequest();
	if (!xhr)
		{
		alert('CORS not supported');
		}
	xhr.open('GET', BASE_URL + "/apphandler?id=" + id, true);
	// Response handlers
	xhr.onreadystatechange = function() {
		if(xhr.readyState == 4)
			{
			if (xhr.status == 200)
				{
				fillAppForm($.parseJSON(xhr.responseText));
				}
			else
				{
				alert("Invocation Errors Occured " + invocation.readyState + " and the status is " + invocation.status);
				}
			}
		};
	xhr.onerror = function() {
		alert('Error requesting application data');
		};

	xhr.send();
	}


function fillAppForm(data)
	{
	//alert(data.application.app_name);
	$("#app_id").val(data.application.app_id);
	$("#app_title").val(data.application.app_name);
	$("#app_description").val(data.application.app_description);
	$("#app_address").val(data.application.app_address);
	$("#app_geoposition").val(data.application.app_geoposition);
	$("#app_telephone").val(data.application.app_telephone);
	$("#app_email").val(data.application.app_email);
	$("#app_website").val(data.application.app_website);
	}
	

function onAppUpdateBtn()
	{
	alert("clicked on update!");
	
	var app_id = $("#app_id").val();
	if(app_id != null && app_id != "")
		{
		$.ajax({
		url: BASE_URL + "/apphandler",
		type: 'PUT',
		data: "id=" + app_id + "&app_title=" + $("#app_title").val() + "&app_description=" + $("#app_description").val() + "&app_address=" + $("#app_address").val() + "&app_geoposition=" + $("#app_geoposition").val() + "&app_telephone=" + $("#app_telephone").val() + "&app_email=" + $("#app_email").val() + "&app_website=" + $("#app_website").val(),
		success: function(data) {
			alert('PUT was performed.');
		}
		});	
		}
	
	/*var app_id = $("#app_id").val();
	if(app_id != null && app_id != "")
		{
		var params = "id=" + app_id + "&app_title=" + $("#app_title").val() + "&app_description=" + $("#app_description").val() + "&app_address=" + $("#app_address").val() + "&app_geoposition=" + $("#app_geoposition").val() + "&app_telephone=" + $("#app_telephone").val() + "&app_email=" + $("#app_email").val() + "&app_website=" + $("#app_website").val();
		alert(params);
		var xhr = new XMLHttpRequest();
		if (!xhr)
			{
			alert('CORS not supported');
			}
		else
			{
			xhr.setRequestHeader('Content-Type','application/x-www-form-urlencoded');
			xhr.open('PUT', BASE_URL + "/apphandler", false);
			// Response handlers
			xhr.onreadystatechange = function() {
				if(xhr.readyState == 4)
					{
					if (xhr.status == 200)
						{
						$.mobile.changePage("#applist_page");
						}
					else
						{
						alert("Invocation Errors Occured " + invocation.readyState + " and the status is " + invocation.status);
						}
					}
				};
			xhr.onerror = function() {
				alert('Error updating application with id ' + app_id);
				};

			xhr.send(params);
			}
		}*/
	}
	
function onAppDeleteBtn()
	{
	alert("clicked on delete!");
	var app_id = $("#app_id").val();
	if(app_id != null && app_id != "")
		{
		var xhr = new XMLHttpRequest();
		if (!xhr)
			{
			alert('CORS not supported');
			}
		xhr.setRequestHeader('Content-Type','application/x-www-form-urlencoded');
		xhr.open('DELETE', BASE_URL + "/apphandler?id=" + app_id, true);
		// Response handlers
		xhr.onreadystatechange = function() {
			if(xhr.readyState == 4)
				{
				if (xhr.status == 200)
					{
					$.mobile.changePage("#applist_page");
					}
				else
					{
					alert("Invocation Errors Occured " + invocation.readyState + " and the status is " + invocation.status);
					}
				}
			};
		xhr.onerror = function() {
			alert('Error deleting application with id ' + app_id);
			};

		xhr.send();
		}
	}
	
/*$("#app_store_btn").click(function() {
        alert('clicked on store');
  });

$("#app_delete_btn").click(function() {
        alert('clicked on delete');
  });*/
	
$(document).ready(function()
	{
	//alert("document ready occurred!");
	requestAppList();
	//callOtherDomain();
	});




// =============================================================================
// === OLD STUFF ===============================================================
// =============================================================================

	


function createAppForm(appdata)
	{
	$.mobile.changePage( "./appedit.html", { role: "page"} );
	//$.mobile.changePage("appedit.html");
	
	/*
// load content from external file
 	$.get("appedit.html", function(data) {
          $('#content').html(data).trigger("create");
        }, "html");
	//
	if(appdata != null)
		{
		alert(appdata.application.app_name);
		//$("#app_title").val(appdata.application.app_name);
		//$('#app_title').textinput('refresh');

		$("#content #app_address").val("kitemmuort!");
		//$("#app_address").textinput();
		
		$('#mainpage').trigger('create');
		}*/
	}



var appedit = { 
	on_delete_btn : function()
		{
		$('input[name=app_edit_action]').val("delete");
		alert($('input[name=app_edit_action]').val() + " - " + $('input[name=appId]').val());
		$("#app_edit_form").submit();
		}
	}

function loadAppList_OLD()
	{
	//var data;
	//$.ajax({ type: "GET", url: "/applist", dataType: "jsonp", success: dumpList(applist) });
		
	$.getJSON("/applist", function(data)
		{
		$("#content").html("");

		$("#content").append("<p>Application list</p>");

		$("#content").append("<ul data-role='listview' data-inset='true' class='ui-listview ui-listview-inset ui-corner-all ui-shadow'>");
		for(var i=0; i < data.applist.length; i++)
			{
			$("#content ul").append("<li><a href='app_edit.jsp?appId=" + data.applist[i].app_id + "' data-transition='slide'>" + data.applist[i].app_name + "</a></li>");
			}
		$("#content ul").listview();
		});
	alert("fuuuuuuck");
	}


/*$("#app_edit_delete").click(function() {
        alert('clicked on delete');
  });*/